package com.yuan.controller;

import com.yuan.dto.StudentDTO;
import com.yuan.pojo.Student;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TestValidateController {

    @GetMapping("/testValidate")
    public String testValidate(@RequestBody @Valid StudentDTO studentDTO
    , BindingResult br) {

        if (br.hasErrors()) {
            Map<String,Object> errorMap = new HashMap<>();
            List<FieldError> fieldErrors = br.getFieldErrors();
            fieldErrors.forEach(fieldError -> {
                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            });
            return errorMap.toString();
            }


        System.out.println("studentDTO = " + studentDTO);


        return "testValidate";
    }

}
